package com.zh.common.view

import android.annotation.SuppressLint
import android.content.Context
import android.content.res.ColorStateList
import android.graphics.Color
import android.graphics.Typeface
import android.graphics.drawable.Drawable
import android.os.Build
import android.text.InputFilter
import android.util.AttributeSet
import android.util.TypedValue
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.core.graphics.drawable.DrawableCompat
import androidx.core.view.isVisible
import com.blankj.utilcode.util.SizeUtils
import com.zh.common.R
import com.zh.common.ktx.inflate
import com.zh.common.ktx.sp2px

/**
 * 自定义通用的左右文字加图片控件
 */
@SuppressLint("UseCompatTextViewDrawableApis")
class RelativeItemView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {

    private val view by lazy {
        context.inflate(R.layout.layout_item_relative)
    }

    /**
     * 控件
     */
    private val mIvLeftImg by lazy { view.findViewById<ImageView>(R.id.ivLeftImg) }//左边图片
    private val mTvLeft by lazy { view.findViewById<TextView>(R.id.tvLeft) }//左边文字
    private val mEtContent by lazy { view.findViewById<EditText>(R.id.etContent) }//输入框文字
    private val mTvRight by lazy { view.findViewById<TextView>(R.id.tvRight) }//右边文字
    private val mViewDriver by lazy { view.findViewById<View>(R.id.viewDriver) }//底部横线

    /**
     * 左边文字
     */
    private val defaultLeftTextColor = R.color.color_text_333//默认左边文字颜色
    private val defaultLeftTextSize = 14f//默认左边文字大小
    private val defaultLeftTextPaddingLeft = 15f//默认左边文字PaddingLeft
    private val defaultLeftDrawablePadding = 5f//默认左边DrawablePadding

    /**
     * 输入框
     */
    private val defaultEditTextColor = R.color.color_text_333//默认输入框文字颜色
    private val defaultEditTextHintColor = R.color.color_text_999//默认输入框提示文字颜色
    private val defaultEditTextSize = 14f//默认输入框文字大小
    private val defaultEditTextBackgroundColor = Color.WHITE//默认输入框背景色

    /**
     * 右边文字
     */
    private val defaultRightTextColor = R.color.color_text_666//默认右边文字颜色
    private val defaultRightTextSize = 14f//默认右边文字大小
    private val defaultRightTextPaddingRight = 15f//默认右边文字PaddingRight
    private val defaultRightDrawablePadding = 5f//默认右边DrawablePadding

    /**
     * 底部横线
     */
    private val defaultDriverColor = R.color.color_line//默认底部横线颜色

    init {
        removeAllViews()
        addView(view)
        mTvRight.gravity = Gravity.RIGHT or Gravity.CENTER_VERTICAL

        val typedArray =
            context.obtainStyledAttributes(attrs, R.styleable.RelativeItemView, defStyleAttr, 0)

        /**
         * 左边图片
         */
        if (typedArray.hasValue(R.styleable.RelativeItemView_riv_leftImg)) {
            //左边文字PaddingLeft - 默认5dp
            mTvLeft.setPadding(SizeUtils.dp2px(5f), 0, 0, 0)
            mIvLeftImg.setImageDrawable(typedArray.getDrawable(R.styleable.RelativeItemView_riv_leftImg))
            val lp = mIvLeftImg.layoutParams as RelativeLayout.LayoutParams
            //左边图片设置宽高
            if (typedArray.hasValue(R.styleable.RelativeItemView_riv_leftImgWidth)) {
                lp.width = typedArray.getDimension(
                    R.styleable.RelativeItemView_riv_leftImgWidth,
                    ViewGroup.LayoutParams.WRAP_CONTENT.toFloat()
                ).toInt()
            }
            if (typedArray.hasValue(R.styleable.RelativeItemView_riv_leftImgHeight)) {
                lp.height = typedArray.getDimension(
                    R.styleable.RelativeItemView_riv_leftImgHeight,
                    ViewGroup.LayoutParams.WRAP_CONTENT.toFloat()
                ).toInt()
            }
            mIvLeftImg.layoutParams = lp
            mIvLeftImg.isVisible = true
        } else {
            mIvLeftImg.isVisible = false
        }

        /**
         * 左边文字
         */
        if (typedArray.hasValue(R.styleable.RelativeItemView_riv_leftText)) {
            mTvLeft.text = typedArray.getString(R.styleable.RelativeItemView_riv_leftText)
        }
        //左边文字颜色
        if (typedArray.hasValue(R.styleable.RelativeItemView_riv_leftTextColor)) {
            mTvLeft.setTextColor(
                typedArray.getColor(
                    R.styleable.RelativeItemView_riv_leftTextColor,
                    ContextCompat.getColor(context, defaultLeftTextColor)
                )
            )
        } else {
            mTvLeft.setTextColor(ContextCompat.getColor(context, defaultLeftTextColor))
        }
        //左边文字字体大小
        val size = if (typedArray.hasValue(R.styleable.RelativeItemView_riv_leftTextSize)) {
            typedArray.getDimension(
                R.styleable.RelativeItemView_riv_leftTextSize, 0f
            )
        } else {
            SizeUtils.sp2px(defaultLeftTextSize).toFloat()
        }
        mTvLeft.setTextSize(TypedValue.COMPLEX_UNIT_PX, size)
        //左边文字PaddingLeft
        if (typedArray.hasValue(R.styleable.RelativeItemView_riv_leftTextPaddingLeft)) {
            mTvLeft.setPadding(
                typedArray.getDimension(
                    R.styleable.RelativeItemView_riv_leftTextPaddingLeft,
                    SizeUtils.dp2px(defaultLeftTextPaddingLeft).toFloat()
                ).toInt(), 0, 0, 0
            )
        }
        //左边文字加粗设置
        if (typedArray.hasValue(R.styleable.RelativeItemView_riv_leftTextStyle)) {
            mTvLeft.typeface = when (typedArray.getInt(
                R.styleable.RelativeItemView_riv_leftTextStyle, 0
            )) {
                1 -> Typeface.defaultFromStyle(Typeface.BOLD)
                2 -> Typeface.defaultFromStyle(Typeface.ITALIC)
                else -> Typeface.defaultFromStyle(Typeface.NORMAL)
            }
        }
        //左边文字Drawable图片
        if (typedArray.hasValue(R.styleable.RelativeItemView_riv_leftTextDrawable)) {
            //左边文字_drawableLeft图片是否在左右
            if (typedArray.hasValue(R.styleable.RelativeItemView_riv_leftTextDrawableRight)) {//显示在右边边
                mTvLeft.setCompoundDrawablesRelativeWithIntrinsicBounds(
                    null, null,
                    typedArray.getDrawable(R.styleable.RelativeItemView_riv_leftTextDrawable), null
                )
            } else {//显示在左边
                mTvLeft.setCompoundDrawablesRelativeWithIntrinsicBounds(
                    typedArray.getDrawable(R.styleable.RelativeItemView_riv_leftTextDrawable),
                    null, null, null
                )
            }
            //左边文字Drawable图片Padding
            if (typedArray.hasValue(R.styleable.RelativeItemView_riv_leftTextDrawablePadding)) {
                mTvLeft.compoundDrawablePadding = typedArray.getDimension(
                    R.styleable.RelativeItemView_riv_leftTextDrawablePadding,
                    SizeUtils.dp2px(defaultLeftDrawablePadding).toFloat()
                ).toInt()
            }
            //左边文字Drawable图片Tint
            if (typedArray.hasValue(R.styleable.RelativeItemView_riv_leftTextDrawableTint)) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    mTvLeft.compoundDrawableTintList = ColorStateList.valueOf(
                        typedArray.getColor(
                            R.styleable.RelativeItemView_riv_leftTextDrawableTint, 0
                        )
                    )
                }
            }
        }
        /**
         * 输入框
         */
        if (typedArray.hasValue(R.styleable.RelativeItemView_riv_editText) ||
            typedArray.hasValue(R.styleable.RelativeItemView_riv_editTextHint) ||
            typedArray.hasValue(R.styleable.RelativeItemView_riv_editTextColor) ||
            typedArray.hasValue(R.styleable.RelativeItemView_riv_editTextHintColor) ||
            typedArray.hasValue(R.styleable.RelativeItemView_riv_editTextSize)
        ) {
            mEtContent.isVisible = true
            mEtContent.setText(typedArray.getString(R.styleable.RelativeItemView_riv_editText))
            //输入框文字颜色
            val color = if (typedArray.hasValue(R.styleable.RelativeItemView_riv_editTextColor)) {
                typedArray.getColor(
                    R.styleable.RelativeItemView_riv_editTextColor, 0
                )
            } else {
                ContextCompat.getColor(context, defaultEditTextColor)
            }
            mEtContent.setTextColor(color)
            //输入框文字字体大小
            val size = if (typedArray.hasValue(R.styleable.RelativeItemView_riv_editTextSize)) {
                typedArray.getDimension(
                    R.styleable.RelativeItemView_riv_editTextSize, 0f
                )
            } else {
                SizeUtils.sp2px(defaultEditTextSize).toFloat()
            }
            mEtContent.setTextSize(TypedValue.COMPLEX_UNIT_PX, size)
            //输入框文字Hint
            if (typedArray.hasValue(R.styleable.RelativeItemView_riv_editTextHint)) {
                mEtContent.hint =
                    typedArray.getString(R.styleable.RelativeItemView_riv_editTextHint)
            }
            //输入框文字Hint颜色
            val hColor =
                if (typedArray.hasValue(R.styleable.RelativeItemView_riv_editTextHintColor)) {
                    typedArray.getColor(
                        R.styleable.RelativeItemView_riv_editTextHintColor, 0
                    )
                } else {
                    ContextCompat.getColor(context, defaultEditTextHintColor)
                }
            mEtContent.setHintTextColor(hColor)
            //输入框文字加粗设置
            if (typedArray.hasValue(R.styleable.RelativeItemView_riv_editTextStyle)) {
                mEtContent.typeface = when (typedArray.getInt(
                    R.styleable.RelativeItemView_riv_editTextStyle, 0
                )) {
                    1 -> Typeface.defaultFromStyle(Typeface.BOLD)
                    2 -> Typeface.defaultFromStyle(Typeface.ITALIC)
                    else -> Typeface.defaultFromStyle(Typeface.NORMAL)
                }
            }
            //输入框文字背景
            if (typedArray.hasValue(R.styleable.RelativeItemView_riv_editTextBackground)) {
                try {
                    mEtContent.setBackgroundColor(
                        typedArray.getColor(
                            R.styleable.RelativeItemView_riv_editTextBackground,
                            defaultEditTextBackgroundColor
                        )
                    )
                } catch (e: Exception) {
                    mEtContent.background =
                        typedArray.getDrawable(R.styleable.RelativeItemView_riv_editTextBackground)
                    e.printStackTrace()
                }
            }
            //输入框文字是否可编辑
            if (typedArray.hasValue(R.styleable.RelativeItemView_riv_editTextEnabled)) {
                mEtContent.isEnabled =
                    typedArray.getBoolean(R.styleable.RelativeItemView_riv_editTextEnabled, true)
            }
            //输入框文字Gravity位置
            if (typedArray.hasValue(R.styleable.RelativeItemView_riv_editTextGravity)) {
                mEtContent.gravity =
                    when (typedArray.getInt(R.styleable.RelativeItemView_riv_editTextGravity, 0)) {
                        3 -> Gravity.LEFT.or(Gravity.CENTER_VERTICAL)
                        5 -> Gravity.RIGHT.or(Gravity.CENTER_VERTICAL)
                        7 -> Gravity.LEFT.or(Gravity.TOP)
                        else -> Gravity.CENTER_VERTICAL
                    }
            }
            //输入框文字MarginLeft
            val marginLeft =
                if (typedArray.hasValue(R.styleable.RelativeItemView_riv_editTextMarginLeft)) {
                    typedArray.getDimension(R.styleable.RelativeItemView_riv_editTextMarginLeft, 0f)
                } else {
                    0f
                }
            //输入框文字MarginRight
            val marginRight =
                if (typedArray.hasValue(R.styleable.RelativeItemView_riv_editTextMarginRight)) {
                    typedArray.getDimension(
                        R.styleable.RelativeItemView_riv_editTextMarginRight, 0f
                    )
                } else {
                    0f
                }
            val params = mEtContent.layoutParams as RelativeLayout.LayoutParams
            params.setMargins(marginLeft.toInt(), 0, marginRight.toInt(), 0)
            mEtContent.layoutParams = params
            //输入框文字PaddingLeft
            val paddingLeft =
                if (typedArray.hasValue(R.styleable.RelativeItemView_riv_editTextPaddingLeft)) {
                    typedArray.getDimension(
                        R.styleable.RelativeItemView_riv_editTextPaddingLeft,
                        0f
                    )
                } else {
                    0f
                }
            //输入框文字PaddingRight
            val paddingRight =
                if (typedArray.hasValue(R.styleable.RelativeItemView_riv_editTextPaddingRight)) {
                    typedArray.getDimension(
                        R.styleable.RelativeItemView_riv_editTextPaddingRight, 0f
                    )
                } else {
                    0f
                }
            mEtContent.setPadding(paddingLeft.toInt(), 0, paddingRight.toInt(), 0)
            //输入框文字MaxLength
            if (typedArray.hasValue(R.styleable.RelativeItemView_riv_editTextMaxLength)) {
                mEtContent.filters = arrayOf<InputFilter>(
                    InputFilter.LengthFilter(
                        typedArray.getInt(
                            R.styleable.RelativeItemView_riv_editTextMaxLength, EditorInfo.TYPE_NULL
                        )
                    )
                )
            }
            //设置inputType属性
            if (typedArray.hasValue(R.styleable.RelativeItemView_riv_editInputType)) {
                mEtContent.inputType = typedArray.getInt(
                    R.styleable.RelativeItemView_riv_editInputType, EditorInfo.TYPE_NULL
                )
            }
        } else {
            mEtContent.isVisible = false
        }
        /**
         * 右边文字
         */
        if (typedArray.hasValue(R.styleable.RelativeItemView_riv_rightText)) {
            mTvRight.text = typedArray.getString(R.styleable.RelativeItemView_riv_rightText)
        }
        //右边文字颜色
        val rColor = if (typedArray.hasValue(R.styleable.RelativeItemView_riv_rightTextColor)) {
            typedArray.getColor(
                R.styleable.RelativeItemView_riv_rightTextColor, 0
            )
        } else {
            ContextCompat.getColor(context, defaultRightTextColor)
        }
        mTvRight.setTextColor(rColor)
        //右边文字字体大小
        val rSize = if (typedArray.hasValue(R.styleable.RelativeItemView_riv_rightTextSize)) {
            typedArray.getDimension(
                R.styleable.RelativeItemView_riv_rightTextSize, 0f
            )
        } else {
            SizeUtils.sp2px(defaultRightTextSize).toFloat()
        }
        mTvRight.setTextSize(TypedValue.COMPLEX_UNIT_PX, rSize)
        //右边文字hint
        if (typedArray.hasValue(R.styleable.RelativeItemView_riv_rightTextHint)) {
            mTvRight.hint = typedArray.getString(R.styleable.RelativeItemView_riv_rightTextHint)
        }
        val rhColor =
            if (typedArray.hasValue(R.styleable.RelativeItemView_riv_rightTextHintColor)) {
                typedArray.getColor(
                    R.styleable.RelativeItemView_riv_rightTextHintColor, 0
                )
            } else {
                ContextCompat.getColor(context, defaultEditTextHintColor)
            }
        mTvRight.setHintTextColor(rhColor)
        if (typedArray.hasValue(R.styleable.RelativeItemView_riv_rightTextPaddingRight)) {
            //右边文字右边padding
            mTvRight.setPadding(
                0, 0,
                typedArray.getDimension(
                    R.styleable.RelativeItemView_riv_rightTextPaddingRight,
                    SizeUtils.dp2px(defaultRightTextPaddingRight).toFloat()
                ).toInt(), 0
            )
        }
        //右边文字加粗设置
        if (typedArray.hasValue(R.styleable.RelativeItemView_riv_rightTextStyle)) {
            mTvRight.typeface = when (typedArray.getInt(
                R.styleable.RelativeItemView_riv_rightTextStyle, 0
            )) {
                1 -> Typeface.defaultFromStyle(Typeface.BOLD)
                2 -> Typeface.defaultFromStyle(Typeface.ITALIC)
                else -> Typeface.defaultFromStyle(Typeface.NORMAL)
            }
        }
        //右边文字Drawable
        if (typedArray.hasValue(R.styleable.RelativeItemView_riv_rightTextDrawable)) {
            //右边文字Drawable图片
            mTvRight.setCompoundDrawablesRelativeWithIntrinsicBounds(
                null, null,
                typedArray.getDrawable(R.styleable.RelativeItemView_riv_rightTextDrawable),
                null
            )
            //右边文字Drawable图片Padding
            if (typedArray.hasValue(R.styleable.RelativeItemView_riv_rightTextDrawablePadding)) {
                mTvRight.compoundDrawablePadding = typedArray.getDimension(
                    R.styleable.RelativeItemView_riv_rightTextDrawablePadding,
                    SizeUtils.dp2px(defaultRightDrawablePadding).toFloat()
                ).toInt()
            }
            //右边文字Drawable图片Tint
            if (typedArray.hasValue(R.styleable.RelativeItemView_riv_rightTextDrawableTint)) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    mTvRight.compoundDrawableTintList = ColorStateList.valueOf(
                        typedArray.getColor(
                            R.styleable.RelativeItemView_riv_rightTextDrawableTint, 0
                        )
                    )
                }
            }
        }
        /**
         * 下横线
         */
        if (typedArray.hasValue(R.styleable.RelativeItemView_riv_driverShow)
            && typedArray.getBoolean(R.styleable.RelativeItemView_riv_driverShow, false)
        ) {
            mViewDriver.isVisible = true
            //底部横线颜色
            if (typedArray.hasValue(R.styleable.RelativeItemView_riv_driverColor)) {
                mViewDriver.setBackgroundColor(
                    typedArray.getColor(
                        R.styleable.RelativeItemView_riv_driverColor,
                        ContextCompat.getColor(context, defaultDriverColor)
                    )
                )
            }
            val lp = mViewDriver.layoutParams as RelativeLayout.LayoutParams
            //底部横线高度
            lp.height = if (typedArray.hasValue(R.styleable.RelativeItemView_riv_driverHeight)) {
                typedArray.getDimension(
                    R.styleable.RelativeItemView_riv_driverHeight, 0f
                ).toInt()
            } else {
                1
            }
            //底部横线两边距离
            if (typedArray.hasValue(R.styleable.RelativeItemView_riv_driverMarginHorizontal)) {
                val margin = typedArray.getDimension(
                    R.styleable.RelativeItemView_riv_driverMarginHorizontal,
                    0f
                ).toInt()
                lp.leftMargin = margin
                lp.rightMargin = margin
            } else {
                //底部横线左边距离
                if (typedArray.hasValue(R.styleable.RelativeItemView_riv_driverMarginLeft)) {
                    lp.leftMargin = typedArray.getDimension(
                        R.styleable.RelativeItemView_riv_driverMarginLeft, 0f
                    ).toInt()
                }
                //底部横线右边距离
                if (typedArray.hasValue(R.styleable.RelativeItemView_riv_driverMarginRight)) {
                    lp.rightMargin = typedArray.getDimension(
                        R.styleable.RelativeItemView_riv_driverMarginRight, 0f
                    ).toInt()
                }
            }
            mViewDriver.layoutParams = lp
        }
        typedArray.recycle()
    }

    /**
     * 左边图片
     */
    fun getLeftImgView(): ImageView = mIvLeftImg
    fun setLeftImg(res: Int) {
        mIvLeftImg.setImageResource(res)
    }

    fun setLeftImg(res: Drawable) {
        mIvLeftImg.setImageDrawable(res)
    }

    /**
     * 获取左边文字
     */
    fun getLeftTextView(): TextView = mTvLeft
    fun setLeftTextString(src: Any) {
        mTvLeft.text = "$src"
    }

    fun getLeftString(): String = mTvLeft.text.toString()
    fun setLeftClickListener(listener: OnClickListener) {
        mTvLeft.setOnClickListener(listener)
    }

    /**
     * 获取输入框文字
     */
    fun getEditText(): EditText = mEtContent
    fun setEditTextString(src: Any) {
        mEtContent.setText("$src")
    }

    fun setEditTextHint(src: Any) {
        mEtContent.hint = "$src"
    }

    fun getEditString(): String = mEtContent.text.toString()

    /**
     * 获取右边文字
     */
    fun getRightTextView(): TextView = mTvRight
    fun setRightText(src: Any) {
        mTvRight.text = "$src"
    }

    fun setRightImageTint(color: Int) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            mTvRight.compoundDrawableTintList = ColorStateList.valueOf(color)
        } else {
            val drawable = mTvRight.compoundDrawables[0]
            val right = tintListDrawable(drawable, ContextCompat.getColorStateList(context, color))
            mTvRight.setCompoundDrawables(null, null, right, null)
        }
    }

    fun getRightText(): String = mTvRight.text.toString()
    fun setRightClickListener(listener: OnClickListener) {
        mTvRight.setOnClickListener(listener)
    }

    fun setRightImg(res: Int) {
        mTvRight.setCompoundDrawablesRelativeWithIntrinsicBounds(
            0, 0, res, 0
        )
    }

    private fun tintListDrawable(drawable: Drawable, colors: ColorStateList?): Drawable {
        val wrappedDrawable = getCanTintDrawable(drawable)
        DrawableCompat.setTintList(wrappedDrawable, colors)
        return wrappedDrawable
    }

    private fun getCanTintDrawable(drawable: Drawable): Drawable {
        val state = drawable.constantState
        return DrawableCompat.wrap(state?.newDrawable() ?: drawable).mutate()
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        removeAllViews()
    }
}